<template>
  <j-modal
    :title="title"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <a-form :form="form">
                <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="模板编码">
          <a-input placeholder="请输入模板编码" v-decorator="['code', validatorRules.code]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="模板名称">
          <a-input placeholder="请输入模板名称" v-decorator="['name', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="业务类型">
          <j-dict-select-tag  v-decorator="['bizType', validatorRules.bizType ]" placeholder="业务类型" :triggerChange="true" dictCode="print_template_biz_type"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="模板预览图片">
          <a-upload
            listType="picture-card"
            class="logo-uploader"
            :showUploadList="false"
            :action="uploadAction"
            :data="{'isup':1,'dir':'stm/PrintTemplate'}"
            :headers="headers"
            :beforeUpload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="picUrl" :src="getPicView()" alt="logo" style="height:104px;max-width:300px"/>
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import {httpAction, getAction} from '@/api/manage'
  import { duplicateCheck } from '@/api/api'
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  import JDate from '@/components/jeecg/JDate'
  import pick from 'lodash.pick'
  import moment from "moment"
  import Vue from 'vue'

  export default {
    name: 'StmPrintTemplateModal',
    components: {
      JDate
    },
    data() {
      return {
        title: "操作",
        visible: false,
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        confirmLoading: false,
        uploadLoading:false,
        headers:{},
        form: this.$form.createForm(this),
        validatorRules: {
          code: { rules: [{ required: true, message: '请输入模板编码!' },{validator: this.validateCode}] },
          bizType: { rules: [{ required: true, message: '请选择业务类型!' }] }
        },
        picUrl: "",
        url: {
          add: "/stm/stmPrintTemplate/add",
          edit: "/stm/stmPrintTemplate/edit",
          queryByCode: "/stm/stmPrintTemplate/queryByCode",
          stmPrintContentList: '/stm/stmPrintTemplate/queryStmPrintContentByMainId',
          fileUpload: window._CONFIG['domianURL']+"/sys/common/ossUpload",
          imgerver: window._CONFIG['domianURL']+"/sys/common/view",
        }
      }
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token":token};
    },
    computed:{
      uploadAction:function () {
        return this.url.fileUpload;
      }
    },
    methods: {
      add() {
        this.picUrl = "";
        this.edit({});
      },
      edit(record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        //初始化明细表数据
        console.log(this.model.id)

        this.picUrl = this.model.pic;
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'code', 'name', 'bizType', ))
          // 时间格式化
        });
      },
      close() {
        this.$emit('close');
        this.visible = false;
      },
      validateCode(rule, value, callback){
        getAction(this.url.queryByCode, {id:this.model.id,code:value}).then(res => {
          if (res.success && res.result) {
            callback('编码'+value+'已存在');
          }else {
            callback()
          }
        })
      },
      beforeUpload: function(file){
        var fileType = file.type;
        if(fileType.indexOf('image')<0){
          this.$message.warning('请上传图片');
          return false;
        }
        //TODO 验证文件大小
      },
      handleChange (info) {
        this.picUrl = "";
        if (info.file.status === 'uploading') {
          this.uploadLoading = true;
          return
        }
        if (info.file.status === 'done') {
          var response = info.file.response;
          this.uploadLoading = false;
          console.log(response);
          if(response.success){
            this.model.pic = response.message;
            this.picUrl = this.model.pic;
          }else{
            this.$message.warning(response.message);
          }
        }
      },
      getPicView(){
        if(this.model.pic !== null && this.model.pic !== undefined && this.model.pic !== ''){
          if('http' === this.model.pic.substring(0,4)){
            return this.model.pic;
          }
          return this.url.imgerver +"/"+ this.model.pic;
        }
      },
      handleOk() {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                 that.$message.success(res.message);
                 that.$emit('ok');
               } else {
                 that.$message.warning(res.message);
               }
             }).finally(() => {
               that.confirmLoading = false;
               that.close();
             })
           }
        })
      },
      handleCancel() {
        this.close()
      }
    }
  }
</script>

<style scoped>

  .logo-uploader > .ant-upload {
    width:104px;
    height:104px;
  }
  .ant-upload-select-picture-card i {
    font-size: 49px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

  .ant-table-tbody .ant-table-row td{
    padding-top:10px;
    padding-bottom:10px;
  }

  .ant-btn {
    padding: 0 10px;
    margin-left: 3px;
  }

  .ant-form-item-control {
    line-height: 0px;
  }

  /** 主表单行间距 */
  .ant-form .ant-form-item {
    margin-bottom: 10px;
  }

  /** Tab页面行间距 */
  .ant-tabs-content .ant-form-item {
    margin-bottom: 0px;
  }
</style>